package com.atguigu.ucenterservice.service.impl;

import com.atguigu.commonutils.JwtUtils;
import com.atguigu.commonutils.MD5;
import com.atguigu.commonutils.R;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.atguigu.ucenterservice.entity.UcenterMember;
import com.atguigu.ucenterservice.entity.vo.RegisterVo;
import com.atguigu.ucenterservice.mapper.UcenterMemberMapper;
import com.atguigu.ucenterservice.service.UcenterMemberService;
import com.atguigu.ucenterservice.utils.HttpClientUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;

/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author 陈烨庆
 * @since 2022-04-06
 */
@Service
public class UcenterMemberServiceImpl extends ServiceImpl<UcenterMemberMapper, UcenterMember> implements UcenterMemberService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public String login(UcenterMember member) {
        // 获取登录手机号和密码
        String mobile = member.getMobile();
        String password = member.getPassword();

        // 手机号和密码非空判断
        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(password)) {
            throw new GuliException(20001, "登陆失败");
        }

        // 判断手机号是否正确
        QueryWrapper<UcenterMember> memberQueryWrapper = new QueryWrapper<>();
        memberQueryWrapper.eq("mobile", mobile);
        UcenterMember ucenterMember = baseMapper.selectOne(memberQueryWrapper);
        if (ObjectUtils.isEmpty(ucenterMember)) {
            throw new GuliException(20001, "登录失败");
        }

        // 判断密码是否相同
        // 因为存储到数据库中的密码肯定是加密的，需要把输入的密码加密后进行判断
        if (!MD5.encrypt(password).equals(ucenterMember.getPassword())) {
            throw new GuliException(20001, "登陆失败");
        }

        // 判断是否禁用
        if (ucenterMember.getIsDisabled()) {
            throw new GuliException(20001, "用户已被禁用");
        }

        // 登录成功，生成 token
        return JwtUtils.getJwtToken(ucenterMember.getId(), ucenterMember.getNickname());
    }

    @Override
    public R register(RegisterVo registerVo) {
        String mobile = registerVo.getMobile();
        String password = registerVo.getPassword();
        String code = registerVo.getCode();
        String nickname = registerVo.getNickname();
        // 手机号和密码非空判断
        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(password)
                || StringUtils.isEmpty(nickname) || StringUtils.isEmpty(code)) {
            throw new GuliException(20001, "注册失败，内容不能为空");
        }

        // 判断验证码
        String redisCode = redisTemplate.opsForValue().get(mobile);
        if (!code.equals(redisCode)) {
            throw new GuliException(20001, "注册失败，验证码输入错误");
        }

        // 看是否有相同手机号
        QueryWrapper<UcenterMember> ucenterMemberQueryWrapper = new QueryWrapper<>();
        ucenterMemberQueryWrapper.eq("mobile", mobile);
        Integer count = baseMapper.selectCount(ucenterMemberQueryWrapper);
        if (count > 0) {
            throw new GuliException(20001, "注册失败，有相同手机号");
        }

        // 没问题进行插入注册
        UcenterMember ucenterMember = new UcenterMember();
        ucenterMember.setMobile(mobile);
        ucenterMember.setPassword(MD5.encrypt(password));
        ucenterMember.setNickname(nickname);

        int isOk = baseMapper.insert(ucenterMember);
        if (isOk > 0) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    @Override
    public UcenterMember getMemberByOpenId(String openid) {
        QueryWrapper<UcenterMember> ucenterMemberQueryWrapper = new QueryWrapper<>();
        ucenterMemberQueryWrapper.eq("openid", openid);
        ucenterMemberQueryWrapper.last("limit 1");
        UcenterMember ucenterMember = baseMapper.selectOne(ucenterMemberQueryWrapper);
        return ucenterMember;
    }

    /**
     * 拿着 access_token 和 openid 的值再去请求微信提供的固定地址
     * 访问微信的资源服务器，获取用户信息
     * @param openId
     * @param accessToken
     * @return
     */
    @Override
    public HashMap getUserInfo(String openId, String accessToken) {

        String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                "?access_token=%s" +
                "&openid=%s";
        String userInfoUrl = String.format(baseUserInfoUrl, accessToken, openId);

        String resultUserInfo = null;
        try {
            resultUserInfo = HttpClientUtils.get(userInfoUrl);
            System.out.println(resultUserInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Gson gson = new Gson();
        HashMap<String, Object> resultMap = gson.fromJson(resultUserInfo, HashMap.class);
        return resultMap;
    }
}
